package com.rshang.rsdp.service.impl;

import com.rshang.rsdp.annotation.Log;
import com.rshang.rsdp.bean.DataGrid;
import com.rshang.rsdp.bean.Response;
import com.rshang.rsdp.common.status.ExcelStatusCode;
import com.rshang.rsdp.common.status.StatusCode;
import com.rshang.rsdp.common.status.TzjlStatusCode;
import com.rshang.rsdp.common.status.ZhStatusCode;
import com.rshang.rsdp.entity.DmRsdlZhxx;
import com.rshang.rsdp.entity.TbRsdlTzjl;
import com.rshang.rsdp.entity.TbUser;
import com.rshang.rsdp.exception.RsdpSystemException;
import com.rshang.rsdp.kit.StrKits;
import com.rshang.rsdp.mapper.DmRsdlGsaMapper;
import com.rshang.rsdp.mapper.DmRsdlGsbMapper;
import com.rshang.rsdp.mapper.TbRsdlRyxxMapper;
import com.rshang.rsdp.mapper.TbRsdlTzjlMapper;
import com.rshang.rsdp.mapper.TbUserMapper;
import com.rshang.rsdp.service.IExcelService;
import com.rshang.rsdp.service.ITbRsdlTzjlService;
import com.rshang.rsdp.util.excel.CellKey;
import com.rshang.rsdp.util.i18n.I18nMessage;
import com.baomidou.mybatisplus.mapper.Condition;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.usermodel.Workbook;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

/**
 * <p>
 * 调整记录信息表 服务实现类
 * </p>
 *
 * @author zhangjun
 * @since 2017-08-20
 */
@Service
public class TbRsdlTzjlServiceImpl extends ServiceImpl<TbRsdlTzjlMapper, TbRsdlTzjl> implements ITbRsdlTzjlService {

    private static final Logger logger = LoggerFactory.getLogger(TbRsdlTzjlServiceImpl.class);

    @Autowired
    I18nMessage i18n;

    @Autowired
    IExcelService excel;

    @Autowired
    DmRsdlGsaMapper gsMapper;

    @Autowired
    DmRsdlGsbMapper xgsMapper;

    @Autowired
    TbRsdlRyxxMapper ryMapper;

    @Autowired
    TbUserMapper czrMapper;

    private static final List<CellKey> COLUMN_IMPORT = new ArrayList<CellKey>() {{
        add(new CellKey("工号", "1", true));//1字符型 2数字型 3日期型 4日期时间 9其他
        add(new CellKey("公司名称", "1", true));
        add(new CellKey("小公司名称", "1", false));
        add(new CellKey("员工姓名", "1", 100, false));
        add(new CellKey("身份证号码", "1", 30, false));
        add(new CellKey("调整福利", "1", 400, true));
        add(new CellKey("调整日期", "3", 50, true));
    }};

    @Override
    public DataGrid getManagePageList(Page<HashMap> page, HttpServletRequest request, String czr) {
        String gsmc = StrKits.emptyToStr(request.getParameter("gsmc"));
        String xgsmc = StrKits.emptyToStr(request.getParameter("xgsmc"));
        String xm = StrKits.emptyToStr(request.getParameter("xm"));
        String sfzhm = StrKits.emptyToStr(request.getParameter("sfzhm"));
        String cxrqq = StringUtils.isEmpty(request.getParameter("cxyfq")) ? "" : DateTime.parse(request.getParameter("cxyfq"), DateTimeFormat.forPattern("yyyyMM")).dayOfMonth().withMinimumValue().toString("yyyy-MM-dd");
        String cxrqz = StringUtils.isEmpty(request.getParameter("cxyfz")) ? "" : DateTime.parse(request.getParameter("cxyfz"), DateTimeFormat.forPattern("yyyyMM")).dayOfMonth().withMaximumValue().toString("yyyy-MM-dd");
        page.setRecords(this.baseMapper.getTzjlList(page, gsmc, xgsmc, xm, sfzhm, cxrqq, cxrqz, czr));
        return new DataGrid(page.getRecords(), page.getTotal());
    }

    @Log(module = "调整记录", desc = "新建调整记录")
    @Override
    public Response addSave(HttpServletRequest request, String czr) {
        TbRsdlTzjl tzjl = new TbRsdlTzjl();
        tzjl.setTzjlId(StrKits.uuid());
        tzjl.setGsId(StrKits.emptyToStr(request.getParameter("sel_gs")));
        tzjl.setGsbId(StrKits.emptyToStr(request.getParameter("sel_xgs")));
        tzjl.setRyId(StrKits.emptyToStr(request.getParameter("sel_ry")));
        tzjl.setTzjlNr(StrKits.emptyToStr(request.getParameter("ipt_nr")));
        tzjl.setTzjlRq(new DateTime(StrKits.emptyToStr(request.getParameter("tzrq"))).toDate());
        tzjl.setLrr(czr);
        tzjl.setXgr(czr);
        tzjl.setDlr(czr);
        tzjl.setBclxDm("0");

        if (this.baseMapper.insert(tzjl) > 0) {
            return new Response(StatusCode.SUCCESS.getCode(), i18n.getMessage(StatusCode.SUCCESS.getKey()));
        } else {
            return new Response(StatusCode.OPER_FAILED.getCode(), i18n.getMessage(StatusCode.OPER_FAILED.getKey()));
        }
    }

    @Override
    public TbRsdlTzjl get(HttpServletRequest request) {
        TbRsdlTzjl result = this.selectById(StrKits.emptyToStr(request.getParameter("id")));
        if (result == null) {
            throw new RsdpSystemException(TzjlStatusCode.TZJL_NOTFOUND.getCode(), i18n.getMessage(TzjlStatusCode.TZJL_NOTFOUND.getKey()));
        } else {
            return result;
        }
    }

    @Log(module = "调整记录", desc = "调整记录编辑")
    @Override
    public Response editSave(HttpServletRequest request, String czr) {

        String id = StrKits.emptyToStr(request.getParameter("hid_id"));
        TbRsdlTzjl tzjl = this.selectById(id);
        if (tzjl == null) {
            throw new RsdpSystemException(TzjlStatusCode.TZJL_NOTFOUND.getCode(), i18n.getMessage(TzjlStatusCode.TZJL_NOTFOUND.getKey()));
        }
        tzjl.setGsId(StrKits.emptyToStr(request.getParameter("sel_gs")));
        tzjl.setGsbId(StrKits.emptyToStr(request.getParameter("sel_xgs")));
        tzjl.setRyId(StrKits.emptyToStr(request.getParameter("sel_ry")));
        tzjl.setTzjlNr(StrKits.emptyToStr(request.getParameter("ipt_nr")));
        tzjl.setTzjlRq(new DateTime(StrKits.emptyToStr(request.getParameter("tzrq"))).toDate());
        tzjl.setXgr(czr);
        tzjl.setXgsj(new Date());

        if (this.baseMapper.updateAllColumnById(tzjl) > 0) {
            return new Response(StatusCode.SUCCESS.getCode(), i18n.getMessage(StatusCode.SUCCESS.getKey()));
        } else {
            return new Response(StatusCode.OPER_FAILED.getCode(), i18n.getMessage(StatusCode.OPER_FAILED.getKey()));
        }
    }

    @Log(module = "调整记录", desc = "调整记录删除")
    @Override
    public Response deleteSave(HttpServletRequest request, String czr) {
        String ids = StrKits.emptyToStr(request.getParameter("id"));
        List<String> idList = Lists.newArrayList(ids.split(","));

        if (this.baseMapper.deleteBatchIds(idList) == idList.size()) {
            return new Response(StatusCode.SUCCESS.getCode(), i18n.getMessage(StatusCode.SUCCESS.getKey()));
        } else {
            throw new RsdpSystemException(StatusCode.OPER_FAILED.getCode(), i18n.getMessage(StatusCode.OPER_FAILED.getKey()));
        }
    }

    @Log(module = "调整记录", desc = "调整记录分页导出")
    @Override
    public Workbook tzxxListExport(HttpServletRequest request, String czr) {
        String gsmc = StrKits.emptyToStr(request.getParameter("gsmc"));
        String xgsmc = StrKits.emptyToStr(request.getParameter("xgsmc"));
        String xm = StrKits.emptyToStr(request.getParameter("xm"));
        String sfzhm = StrKits.emptyToStr(request.getParameter("sfzhm"));
        String cxrqq = StringUtils.isEmpty(request.getParameter("cxyfq")) ? "" : DateTime.parse(request.getParameter("cxyfq"), DateTimeFormat.forPattern("yyyyMM")).dayOfMonth().withMinimumValue().toString("yyyy-MM-dd");
        String cxrqz = StringUtils.isEmpty(request.getParameter("cxyfz")) ? "" : DateTime.parse(request.getParameter("cxyfz"), DateTimeFormat.forPattern("yyyyMM")).dayOfMonth().withMaximumValue().toString("yyyy-MM-dd");

        List<HashMap> list = this.baseMapper.getTzjlListExport(gsmc, xgsmc, xm, sfzhm, cxrqq, cxrqz, czr);
        Workbook wb = new HSSFWorkbook();
        Sheet sheet = wb.createSheet("数据调整记录");
        Row row = null;
        Cell cell = null;
        int rowIndex = 0;

        //自动列宽
        //sheet.autoSizeColumn(1);
        sheet.setColumnWidth(0, 10000);
        sheet.setColumnWidth(1, 10000);
        sheet.setColumnWidth(2, 5000);
        sheet.setColumnWidth(3, 5000);
        sheet.setColumnWidth(4, 5000);
        sheet.setColumnWidth(5, 10000);
        sheet.setColumnWidth(6, 5000);
        //创建字体
        HSSFFont headFont = (HSSFFont) wb.createFont();
        headFont.setFontHeightInPoints((short) 14);//设置字体大小
        headFont.setBold(true);

        HSSFFont contFont = (HSSFFont) wb.createFont();
        contFont.setFontHeightInPoints((short) 12);//设置字体大小

        HSSFCellStyle headStyle = (HSSFCellStyle) wb.createCellStyle();
        headStyle.setFont(headFont);
        headStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        headStyle.setFillForegroundColor(HSSFColor.HSSFColorPredefined.ORANGE.getIndex());
        headStyle.setBorderBottom(BorderStyle.THIN); //下边框
        headStyle.setBorderLeft(BorderStyle.THIN);//左边框
        headStyle.setBorderTop(BorderStyle.THIN);//上边框
        headStyle.setBorderRight(BorderStyle.THIN);//右边框
        headStyle.setAlignment(HorizontalAlignment.CENTER); // 居中
        headStyle.setVerticalAlignment(VerticalAlignment.CENTER);//垂直集中

        HSSFCellStyle contStyle = (HSSFCellStyle) wb.createCellStyle();
        contStyle.setFont(contFont);
        contStyle.setBorderBottom(BorderStyle.THIN); //下边框
        contStyle.setBorderLeft(BorderStyle.THIN);//左边框
        contStyle.setBorderTop(BorderStyle.THIN);//上边框
        contStyle.setBorderRight(BorderStyle.THIN);//右边框
        contStyle.setAlignment(HorizontalAlignment.CENTER); // 居中
        contStyle.setVerticalAlignment(VerticalAlignment.CENTER);//垂直集中

        //构建表头
        row = sheet.createRow(rowIndex++);
        row.setHeight((short) 500);//行高
        cell = row.createCell(0);
        cell.setCellType(CellType.STRING);
        cell.setCellStyle(headStyle);
        cell.setCellValue("公司名称");

        cell = row.createCell(1);
        cell.setCellType(CellType.STRING);
        cell.setCellStyle(headStyle);
        cell.setCellValue("小公司名称");

        cell = row.createCell(2);
        cell.setCellType(CellType.STRING);
        cell.setCellStyle(headStyle);
        cell.setCellValue("员工姓名");

        cell = row.createCell(3);
        cell.setCellType(CellType.STRING);
        cell.setCellStyle(headStyle);
        cell.setCellValue("身份证号码");

        cell = row.createCell(4);
        cell.setCellType(CellType.STRING);
        cell.setCellStyle(headStyle);
        cell.setCellValue("联系电话");

        cell = row.createCell(5);
        cell.setCellType(CellType.STRING);
        cell.setCellStyle(headStyle);
        cell.setCellValue("录入人");

        cell = row.createCell(6);
        cell.setCellType(CellType.STRING);
        cell.setCellStyle(headStyle);
        cell.setCellValue("调整福利");

        cell = row.createCell(7);
        cell.setCellType(CellType.STRING);
        cell.setCellStyle(headStyle);
        cell.setCellValue("调整日期");

        for (HashMap record : list) {
            row = sheet.createRow(rowIndex++);
            row.setHeight((short) 500);//excel行高*20
            cell = row.createCell(0);
            cell.setCellType(CellType.STRING);
            cell.setCellStyle(contStyle);
            cell.setCellValue(StrKits.emptyToStr(record.get("GS_MC")));

            cell = row.createCell(1);
            cell.setCellType(CellType.STRING);
            cell.setCellStyle(contStyle);
            cell.setCellValue(StrKits.emptyToStr(record.get("GSB_MC")));

            cell = row.createCell(2);
            cell.setCellType(CellType.STRING);
            cell.setCellStyle(contStyle);
            cell.setCellValue(StrKits.emptyToStr(record.get("RY_XM")));

            cell = row.createCell(3);
            cell.setCellType(CellType.STRING);
            cell.setCellStyle(contStyle);
            cell.setCellValue(StrKits.emptyToStr(record.get("RY_ZJHM")));

            cell = row.createCell(4);
            cell.setCellType(CellType.STRING);
            cell.setCellStyle(contStyle);
            cell.setCellValue(StrKits.emptyToStr(record.get("RY_LXFS")));

            cell = row.createCell(5);
            cell.setCellType(CellType.STRING);
            cell.setCellStyle(contStyle);
            cell.setCellValue(StrKits.emptyToStr(record.get("USER_XM")));

            cell = row.createCell(6);
            cell.setCellType(CellType.STRING);
            cell.setCellStyle(contStyle);
            cell.setCellValue(StrKits.emptyToStr(record.get("TZJL_NR")));

            cell = row.createCell(7);
            cell.setCellType(CellType.STRING);
            cell.setCellStyle(contStyle);
            cell.setCellValue(DateTime.parse(StrKits.emptyToStr(record.get("TZJL_RQ")), DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss.SSS")).toString("yyyy-MM-dd"));
        }

        return wb;
    }

    @Transactional
    @Log(module = "调整记录", desc = "调整记录模板导入")
    @Override
    public Response importSave(MultipartFile file, String czr, TbUser user) {
        if (file == null)//文件为空
        {
            throw new RsdpSystemException(ExcelStatusCode.XLS_EMPTY.getCode(), i18n.getMessage(ExcelStatusCode.XLS_EMPTY.getKey()));
        }
        InputStream is = null;
        Workbook wb = null;
        Sheet sheet = null;
        Row row = null;
        List<Row> data = new ArrayList<Row>();
        List<String> errList = new ArrayList<String>();
        Cell cell = null;
        try {
            is = file.getInputStream();
            wb = new HSSFWorkbook(is);

            if (wb.getNumberOfSheets() == 0)//模板必须要有一个sheet表
            {
                throw new RsdpSystemException(ExcelStatusCode.XLS_NOTFORMATED.getCode(), i18n.getMessage(ExcelStatusCode.XLS_NOTFORMATED.getKey()));
            }
            //读取excel文件
            sheet = wb.getSheetAt(0);//读取第一个sheet表
            int rowCount = sheet.getLastRowNum();//获取模板总数
            logger.debug("tzxx importSave row count:{}", rowCount);
            if (rowCount < 2)//空数据
            {
                throw new RsdpSystemException(ExcelStatusCode.XLS_DATAEMPTY.getCode(), i18n.getMessage(ExcelStatusCode.XLS_DATAEMPTY.getKey()));
            }
            Iterator<Row> it = sheet.iterator();
            int rowNo = 0;

            //循环读取数据
            while (it.hasNext()) {
                row = it.next();

                if (row != null && row.getRowNum() > 0) {
                    rowNo = row.getRowNum();
                    //logger.debug("tzjl importSave rowNum:{}",rowNo);
                    //logger.debug("tzjl importSave row:{}",row.getCell(1));
                    for (int i = 0; i < 7; i++) {
                        //设置单元格类型为String
                        excel.setStringCell(row.getCell(i));
                        //模板校验
                        excel.checkCellValue(rowNo+1, i, COLUMN_IMPORT.get(i), row.getCell(i), errList);
                    }

                    //模板校验
                    //excel.checkCell(rowNo, 0, row.getCell(0) != null ? row.getCell(0).getStringCellValue() : "", 0, errList);
                    //excel.checkCell(rowNo, 2, row.getCell(2)!=null?row.getCell(1).getStringCellValue():"", 0,errList);
                    //excel.checkCell(rowNo, 5, row.getCell(5) != null ? row.getCell(5).getStringCellValue() : "", 400, errList);
                    //excel.checkDateCell(rowNo, 6, row.getCell(6) != null ? row.getCell(6).getStringCellValue() : "", "yyyy-MM-dd", errList, true);

                    if (errList.size() > 0) {
                        if (!data.isEmpty()) {
                            data.clear();
                        }
                    } else {
                        data.add(row);
                    }
                }

            }

        } catch (IOException e) {
            logger.error("tzxx importSave error:{}", e.getMessage());
            throw new RsdpSystemException(StatusCode.SERVER_ERROR.getCode(), e.getMessage());
        } finally {
            try {
                //关闭流及文件
                wb.close();
                is.close();
            } catch (IOException e) {
                logger.error("tzxx importSave close error:{}", e.getMessage());
            }
        }
        int count = 0;
        if (errList.size() > 0)//模板校验错误直接抛出
        {
            return new Response(ExcelStatusCode.XLS_ERROR.getCode(), i18n.getMessage(ExcelStatusCode.XLS_ERROR.getKey(), new Object[]{Joiner.on("").join(errList)}));
        } else {
            logger.debug("tzxx importSave dataList:{}", data);
            List<HashMap> gsList = gsMapper.getGsByCzr("");//获取操作人公司列表
            List<HashMap> xgsList = xgsMapper.getXgsByCzr("");//获取操作人小公司列表
            List<HashMap> ryList = ryMapper.getRyxxByCzr("");//获取操作人人员列表
            List<HashMap> czrList = czrMapper.getYxUserList("");//获取用户列表
            //List<HashMap> bsList = new ArrayList<HashMap>();//已插入成功列表
            String gsid = null;
            String xgsid = null;
            String ryid = null;
            String lrr = null;
            String plId = StrKits.uuid();
            Map<String, String> gsMap = new HashMap<String, String>();
            Map<String, String> xgsMap = new HashMap<String, String>();
            Map<String, String> czrMap = new HashMap<String, String>();

            for (Row tr : data) {
                //如果非业务经理角色人员只能上传自己的数据调整记录
                /*if (!StringUtils.isEmpty(czr) && (!user.getUserGh().equals(tr.getCell(0).getStringCellValue()))) {
                    continue;
                }*/
                //公司、小公司、员工均不为空时
                if (excel.isCellNotEmpty(tr.getCell(1)) && excel.isCellNotEmpty(tr.getCell(2)) && excel.isCellNotEmpty(tr.getCell(3))) {
                    logger.debug("执行公司、小公司、员工均不为空代码");
                    gsid = getGsListId(excel.getCellValue(tr.getCell(1)), gsList, gsMap);
                    if (StringUtils.isEmpty(gsid)) {
                        logger.debug("tzxx importSave gsmc:{} gsid is empty record skip!", tr.getCell(1).getStringCellValue().trim());
                        continue;
                    }
                    xgsid = getXgsListId(gsid, excel.getCellValue(tr.getCell(1)), excel.getCellValue(tr.getCell(2)), xgsList, xgsMap);
                    //logger.debug("执行公司、小公司不为空 员工为空代码 gs:{} xgs:{}", gsid, xgsid);
                    if (StringUtils.isEmpty(xgsid)) {
                        logger.debug("tzxx importSave xgsmc:{} xgsid is empty record skip!", tr.getCell(2).getStringCellValue().trim());
                        continue;
                    }
                    ryid = getRyListId(gsid, xgsid, excel.getCellValue(tr.getCell(3)), excel.getCellValue(tr.getCell(4)), ryList);
                    if (StringUtils.isEmpty(ryid)) {
                        logger.debug("tzxx importSave lrrmc:{} lrr is empty record skip!", tr.getCell(3).getStringCellValue().trim());
                        continue;
                    }
                    lrr = getCzrListId(excel.getCellValue(tr.getCell(0)), czrList);

                    if (insertTzjl(plId, gsid, xgsid, ryid, excel.getCellValue(tr.getCell(5)), excel.getCellValue(tr.getCell(6)), lrr)) {
                        return new Response(StatusCode.OPER_FAILED.getCode(), i18n.getMessage(StatusCode.OPER_FAILED.getKey()));
                    }
                    count++;
                    addCache(excel.getCellValue(tr.getCell(0)), excel.getCellValue(tr.getCell(1)), excel.getCellValue(tr.getCell(2)), excel.getCellValue(tr.getCell(3)), excel.getCellValue(tr.getCell(4)), gsid, xgsid, ryid, lrr, gsMap, xgsMap, czrMap);

                }
                //公司、小公司不为空 员工为空
                if (excel.isCellNotEmpty(tr.getCell(1)) && excel.isCellNotEmpty(tr.getCell(2)) && !excel.isCellNotEmpty(tr.getCell(3))) {
                    logger.debug("执行公司、小公司不为空 员工为空代码");
                    gsid = getGsListId(excel.getCellValue(tr.getCell(1)), gsList, gsMap);
                    if (StringUtils.isEmpty(gsid)) {
                        logger.debug("tzxx importSave gsmc:{} gsid is empty record skip!", tr.getCell(1).getStringCellValue().trim());
                        continue;
                    }
                    xgsid = getXgsListId(gsid, excel.getCellValue(tr.getCell(1)), excel.getCellValue(tr.getCell(2)), xgsList, xgsMap);
                    //logger.debug("执行公司、小公司不为空 员工为空代码 gs:{} xgs:{}", gsid, xgsid);
                    if (StringUtils.isEmpty(xgsid)) {
                        logger.debug("tzxx importSave xgsmc:{} xgsid is empty record skip!", tr.getCell(2).getStringCellValue().trim());
                        continue;
                    }
                    lrr = getCzrListId(excel.getCellValue(tr.getCell(0)), czrList);
                    if (insertTzjl(plId, gsid, xgsid, ryid, excel.getCellValue(tr.getCell(5)), excel.getCellValue(tr.getCell(6)), lrr)) {
                        return new Response(StatusCode.OPER_FAILED.getCode(), i18n.getMessage(StatusCode.OPER_FAILED.getKey()));
                    }
                    count++;
                    addCache(excel.getCellValue(tr.getCell(0)), excel.getCellValue(tr.getCell(1)), excel.getCellValue(tr.getCell(2)), excel.getCellValue(tr.getCell(3)), excel.getCellValue(tr.getCell(4)), gsid, xgsid, "", lrr, gsMap, xgsMap, czrMap);
                }
                //公司不为空 小公司和员工均为空
                if (excel.isCellNotEmpty(tr.getCell(1)) && !excel.isCellNotEmpty(tr.getCell(2)) && !excel.isCellNotEmpty(tr.getCell(3))) {
                    logger.debug("执行公司不为空 小公司和员工均为空代码");
                    gsid = getGsListId(excel.getCellValue(tr.getCell(1)), gsList, gsMap);
                    if (StringUtils.isEmpty(gsid)) {
                        logger.debug("tzxx importSave gsmc:{} gsid is empty record skip!", tr.getCell(1).getStringCellValue().trim());
                        continue;
                    }
                    lrr = getCzrListId(excel.getCellValue(tr.getCell(0)), czrList);
                    if (insertTzjl(plId, gsid, xgsid, ryid, excel.getCellValue(tr.getCell(5)), excel.getCellValue(tr.getCell(6)), lrr)) {
                        return new Response(StatusCode.OPER_FAILED.getCode(), i18n.getMessage(StatusCode.OPER_FAILED.getKey()));
                    }
                    count++;
                    addCache(excel.getCellValue(tr.getCell(0)), excel.getCellValue(tr.getCell(1)), excel.getCellValue(tr.getCell(2)), excel.getCellValue(tr.getCell(3)), excel.getCellValue(tr.getCell(4)), gsid, xgsid, "", lrr, gsMap, xgsMap, czrMap);
                }
                gsid = "";
                xgsid = "";
                ryid = "";
                lrr = "";
            }
        }

        return new Response(StatusCode.SUCCESS.getCode(), i18n.getMessage(ExcelStatusCode.XLS_SUCCESS.getKey(), new Object[]{count}));
    }

    public String getGsListId(String str, List<HashMap> gsList, Map<String, String> gsMap) {
        if (StringUtils.isNotEmpty(gsMap.get(str))) {
            return Objects.toString(gsMap.get(str), "");
        }
        for (HashMap map : gsList) {
            if (str.equals(map.get("GS_MC"))) {
                return Objects.toString(map.get("GS_ID"), "");
            }
        }
        return "";
    }

    public String getXgsListId(String gsid, String gsmc, String str, List<HashMap> xgsList, Map<String, String> xgsMap) {
        if (StringUtils.isNotEmpty(xgsMap.get(gsmc + str))) {
            return Objects.toString(xgsMap.get(gsmc + str), "");
        }
        for (HashMap map : xgsList) {
            if (str.equals(map.get("GSB_MC")) && gsid.equals(map.get("GS_ID"))) {
                return Objects.toString(map.get("GSB_ID"), "");
            }
        }
        return "";
    }

    public void addCache(String gh, String gsmc, String xgsmc, String xm, String sfzhm, String gsid, String xgsid, String ryid, String lrr, Map gsMap, Map xgsMap, Map czrMap) {
        //缓存已保存对象
        gsMap.put(gsmc, gsid);
        if (StringUtils.isNotEmpty(xgsid)) {
            xgsMap.put(gsmc + xgsmc, xgsid);
        }
        if (StringUtils.isNotEmpty(ryid)) {
            xgsMap.put(gsmc + xgsmc + xm + sfzhm, xgsid);
        }
        czrMap.put(gh, lrr);
        //logger.debug("缓存更新 gsMap:{}",gsMap);
        //logger.debug("缓存更新 xgsMap:{}",xgsMap);
        //logger.debug("缓存更新 czrMap:{}",czrMap);
    }

    public boolean insertTzjl(String plId, String gsid, String xgsid, String ryid, String nr, String tzrq, String lrr) {
        TbRsdlTzjl tzjl = new TbRsdlTzjl();
        tzjl.setTzjlId(StrKits.uuid());
        tzjl.setGsId(gsid);
        tzjl.setGsbId(xgsid);
        tzjl.setRyId(ryid);
        tzjl.setTzjlNr(nr);
        tzjl.setTzjlRq(new DateTime(tzrq).toDate());
        tzjl.setLrr(lrr);
        tzjl.setXgr(lrr);
        tzjl.setDlr(lrr);
        tzjl.setBclxDm("1");
        tzjl.setPlBs(plId);
        return this.baseMapper.insert(tzjl) < 0;
    }

    private String getCzrListId(String gh, List<HashMap> list) {
        for (HashMap map : list) {
            if (gh.equals(map.get("USER_GH"))) {
                return Objects.toString(map.get("USER_ID"), "");
            }
        }
        return "";
    }

    private String getRyListId(String gsid, String xgsid, String str, String sfzhm, List<HashMap> list) {
        if (StringUtils.isEmpty(gsid)) {
            return "";
        }
        if (StringUtils.isEmpty(xgsid)) {
            return "";
        }
        for (HashMap map : list) {
            if (((str.equals(map.get("RY_XM")) && sfzhm.equals(map.get("RY_ZJHM"))) || str.equals(map.get("RY_XM"))) && gsid.equals(map.get("GS_ID")) && xgsid.equals(map.get("GSB_ID"))) {
                //logger.debug("getRyListId str:{},sfzhm:{},gsid:{},xgsid:{} map:{}", str, sfzhm, gsid, xgsid, map);
                return Objects.toString(map.get("RY_ID"), "");
            }
        }
        return "";
    }


}
